package com.huluobo.a2212mdmdemo.pages

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Send
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.lib_base.BaseTitle
import com.hyphenate.EMCallBack
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMMessage.ChatType
import com.hyphenate.chat.EMTextMessageBody
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

/**
 *  Created by LC on 2025/6/10.
 */
data class ChatBean(val contact: String, val chatType: ChatType, val groupName: String)

@Composable
fun ChatPage(navHostController: NavHostController, json: String) {
    val chatBean = Gson().fromJson(json, ChatBean::class.java)

    val messageList = remember {
        SnapshotStateList<EMMessage>()
    }

    var messageString by remember {
        mutableStateOf("")
    }

    //是否展示发送消息的进度条
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    var isShowError by remember {
        mutableStateOf(false)
    }
    //当前列表的状态
    val listState = rememberLazyListState()

    //控制列表滚动到最下方的协程
    val coroutineScope = rememberCoroutineScope()

    //声明消息监听器
    val messageListener = EMMessageListener {
        messageList.addAll(it)
        coroutineScope.launch {
            listState.scrollToItem(messageList.size - 1)
        }
    }

    //当前compose控件的生命周期
    DisposableEffect(Unit) {
        //带生命周期的协程作用域
        //初始化时添加消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener)

        //销毁时移除监听器
        onDispose {
            EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        }
    }

    Scaffold(bottomBar = {
        OutlinedTextField(
            value = messageString,
            onValueChange = { messageString = it },
            Modifier.fillMaxWidth(),
            trailingIcon = {
                Icon(imageVector = Icons.Default.Send, contentDescription = "", Modifier.clickable {
                    if (messageString.isNotEmpty()) {
                        isShowProgress = true
                        //构建一条文本消息,第一个参数是消息内容,第二个参数是对方的名字
                        val emMessage = EMMessage.createTextSendMessage(messageString, chatBean.contact)
                        //设置消息类型,单聊和群聊需要不同的类型
                        emMessage.chatType = chatBean.chatType
                        //设置消息发送的监听
                        emMessage.setMessageStatusCallback(object : EMCallBack {
                            override fun onSuccess() {
                                isShowProgress = false
                                messageString = ""
                                coroutineScope.launch {
                                    listState.scrollToItem(messageList.size - 1)
                                }
                            }

                            override fun onError(code: Int, error: String?) {
                                isShowProgress = false
                                isShowError = true
                                ToastUtils.showLong("发送消息失败")
                            }
                        })
                        messageList.add(emMessage)
                        //发送消息
                        EMClient.getInstance().chatManager().sendMessage(emMessage)
                    }
                })
            })
    }) {
        Column(
            Modifier
                .padding(it)
                .padding(20.dp)
                .fillMaxWidth()
        ) {
            if (chatBean.chatType == EMMessage.ChatType.GroupChat) {
                BaseTitle(title = chatBean.groupName, navHostController = navHostController)
            } else {
                BaseTitle(title = "与${chatBean.contact}聊天", navHostController = navHostController)
            }
            Spacer(modifier = Modifier.height(10.dp))
            LazyColumn(state = listState, verticalArrangement = Arrangement.spacedBy(10.dp), content = {
                items(messageList) { message ->
                    ChatItem(message = message, isShowProgress, isShowError, true) {
                        //重新发送消息
                        isShowProgress = true
                        messageList.add(message)
                        //构建一条文本消息,第一个参数是消息内容,第二个参数是对方的名字
                        val emMessage = EMMessage.createTextSendMessage(
                            (message.body as EMTextMessageBody).message,
                            chatBean.contact
                        )
                        //设置消息类型,单聊和群聊需要不同的类型
                        emMessage.chatType = chatBean.chatType
                        //设置消息发送的监听
                        emMessage.setMessageStatusCallback(object : EMCallBack {
                            override fun onSuccess() {
                                isShowProgress = false
                                isShowError = false
                                messageString = ""
                            }

                            override fun onError(code: Int, error: String?) {
                                isShowProgress = false
                                isShowError = true
                                ToastUtils.showLong("发送消息失败")
                            }
                        })
                        //发送消息
                        EMClient.getInstance().chatManager().sendMessage(emMessage)
                    }
                }
            })
        }
    }
}

@Composable
fun ChatItem(message: EMMessage, isShowProgress: Boolean, isShowError: Boolean, isLast: Boolean, retry: () -> Unit) {
    when (message.direct()) {
        EMMessage.Direct.SEND -> {
            Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = "$time", color = Color.LightGray, fontSize = 13.sp)
                Row(
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .padding(10.dp)
                        .fillMaxWidth()
                ) {
                    //如果是最后一条消息,才展示error或者进度条
                    Log.e("TagA", "isLast:$isLast")
                    if (isLast) {
                        if (isShowProgress) {
                            CircularProgressIndicator(Modifier.size(20.dp))
                        }
                        if (isShowError) {
                            Image(imageVector = Icons.Default.Warning, contentDescription = "", Modifier.clickable {
                                retry()
                            })
                        }
                    }
                    Spacer(modifier = Modifier.width(5.dp))
                    Text(text = (message.body as EMTextMessageBody).message)
                    Spacer(modifier = Modifier.width(10.dp))
                    AsyncImage(
                        model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                        contentDescription = "",
                        modifier = Modifier
                            .size(40.dp)
                            .clip(RoundedCornerShape(5.dp)),
                        contentScale = ContentScale.Crop
                    )
                }
            }
        }

        EMMessage.Direct.RECEIVE -> {
            Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = "$time", color = Color.LightGray, fontSize = 13.sp)
                Row(
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .padding(10.dp)
                        .fillMaxWidth()
                ) {
                    AsyncImage(
                        model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                        contentDescription = "",
                        modifier = Modifier
                            .size(40.dp)
                            .clip(RoundedCornerShape(5.dp)),
                        contentScale = ContentScale.Crop
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    Text(text = (message.body as EMTextMessageBody).message)
                }
            }
        }
    }
}